package ui 
{
	import com.greensock.loading.data.SWFLoaderVars;
	import flash.display.InteractiveObject;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	
	/**
	 * ...
	 * @author liwei
	 */
	[Event(name="progress", type="flash.events.ProgressEvent")]
	public class UIPorgressBar extends EventDispatcher
	{
		private var _back:InteractiveObject;
		private var _btn:InteractiveObject;
		private var _width:int;
		private var _btnWidth:int;
		private var _draging:Boolean;
		private var _left:Number;
		private var _inc:Number;
		private var _stage:Stage;
		private var _enable:Boolean;
		public function UIPorgressBar() 
		{
			super();
			_enable = true;
		}
		public function setSkin(back:InteractiveObject, btn:InteractiveObject):void {
			_back = back;
			_btn = btn;
			_width = _back.width;
			_btnWidth = _btn.width;
			_left = back.x;
			_inc = _width - _btnWidth;
			_stage = Config.stage;
			_back.addEventListener(MouseEvent.MOUSE_DOWN, backMouseHandler);
			_btn.mouseEnabled = false;
		}
		
		public function setProgress(progress:Number):void {
			if (_draging) return;
			updateProgress(progress);
		}
		
		private function backMouseHandler(e:MouseEvent):void 
		{
			if (!_enable) return;
			var type:String = e.type;
			var inc:Number = _back.mouseX;
			if (inc < 0) {
				inc = 0;
			}
			if (inc > _width) {
				inc = _width;
			}
			if (type == MouseEvent.MOUSE_MOVE) {
				updateProgress(inc / _width);
			}else if (type == MouseEvent.MOUSE_DOWN) {
				_stage.addEventListener(MouseEvent.MOUSE_UP, backMouseHandler);
				_stage.addEventListener(MouseEvent.MOUSE_MOVE, backMouseHandler);
				_draging = true;
				updateProgress(inc / _width);
			}else if (type == MouseEvent.MOUSE_UP) {
				_stage.removeEventListener(MouseEvent.MOUSE_UP, backMouseHandler);
				_stage.removeEventListener(MouseEvent.MOUSE_MOVE, backMouseHandler);
				_draging = false;
			}
			dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, inc, _width));
		}
		private function updateProgress(progress:Number):void {
			if (progress < 0) {
				progress = 0;
			}
			if (progress > 1) {
				progress = 1;
			}
			_btn.x = _left + _inc * progress;
		}
		
		public function get draging():Boolean 
		{
			return _draging;
		}
		
		public function get enable():Boolean 
		{
			return _enable;
		}
		
		public function set enable(value:Boolean):void 
		{
			_enable = value;
			_btn.visible = _enable;
		}
		
	}

}